// pages/dashboard/dashboard.js
var session = require('../../common/session')
import * as echarts from '../../ec-canvas/echarts';
var config = require('../../common/config');
var totalThis,
putCanClick=true,
bodyWidth,chart,
totalYearChart,
curTotalNumObj,
orderListInfo={"dataX":["1","2"],"dataYs":{"订单数量":[0,0],"发货数量":[0,0],"完成数量":[0,0]}},
totalMonthOrdersCanvas,
requestNum=2,
stackArr,
wechatUserInfo,
    curMonth='1',
    curOrderName,
    totalYearChart,
    totalYearMonthChart,
    totalMonthOrdersChart,
    totalOrderInfoChart,
    totalYearChartData=[{"name":"订单数量","value":0},{"name":"发货数量","value":0},{"name":"完成数量","value":0}],
    totalYearChartOtherOption,
    totalYearMonthData={"dataX":["1月","2月","3月","4月","5月","6月","7月","8月","9月","10月","11月","12月"],"dataY":[0,0,0,0,0,0,0,0,0,0,0,0]},
    totalYearMonthOtherOption,
    orderInfoData=[{"value":0,"name":"工序一0"},{"value":0,"name":"工序二0"},{"value":0,"name":"工序三0"},{"value":0,"name":"完成任务"}],
    valueYears= '2021';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    showChildBox: false,
    showDashboardBox : false,
    optionYears:[
      { text: 2021, value: 2021 },
      { text: 2020, value: 2020 },
      { text: 2019, value: 2019 }
    ],
    valueYears: 2021,
    curTotalNumObj: {},
    curMonth:'',
    curOrderName:'',
    totalYearChart: null,
    totalYearMonthChart: null,
    totalMonthOrdersChart: null,
    totalOrderInfoChart: null,
    yearTotalPie: {
      onInit: function(canvas, width, height, dpr){
        if(!totalYearChart && canvas){
              const chart = echarts.init(canvas, null, {
                width: width,
                height: height,
                devicePixelRatio: dpr // new
              });
              totalYearChart = chart;
              canvas.setChart(totalYearChart);
        } 
        if(totalYearChart) {
            var option = {
              color:['#E68853','#5ECFFF','#F5D77B'],
              series: [{
                label: {
                  normal: {
                    fontSize: 14
                  }
                },
                type: 'pie',
                center: ['50%', '60%'],
                radius: ['50%','70%'],
                data: totalYearChartData,
                label: {
                  show: false,
                  position: 'center'
                },
                emphasis: {
                    label: {
                        show: true,
                        fontSize: '14',
                        fontWeight: 'bold'
                    }
                },
                labelLine: {
                    show: false
                  
                },
                itemStyle: {
                    borderRadius: 10,
                    borderColor: '#fff',
                    borderWidth: 2
                }
              }]
            };
            totalYearChart.setOption(option);
            return totalYearChart; 
        }
      }
    },
    yearEachMonthBar: {
      onInit: function(canvas, width, height, dpr){
        if(totalYearMonthChart){

        } else if(canvas){
            chart = echarts.init(canvas, null, {
              width: width,
              height: height,
              devicePixelRatio: dpr // new
            });
            totalYearMonthChart = chart;
            canvas.setChart(totalYearMonthChart);
          }
      
        if(totalYearMonthChart && totalYearMonthData){
          var option = {
            title: {
              text: '每月订单统计',
              subtext: '',
              left: 0,
              top:0,
              textStyle: {
                  fontSize:'14',
                  fontWeight: 600
             }
          },
            tooltip: {
              trigger: 'axis',
              axisPointer: {            // 坐标轴指示器，坐标轴触发有效
                type: 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
              },
              confine: true
            },
            grid: {
              top: 40,
              bottom: 24,
              left: '0%',
              right: 20,
              containLabel: true
            },
            yAxis: [
              {
                type: 'value',
                axisLine: {
                  lineStyle: {
                    color: '#999'
                  }
                },
                axisLabel: {
                  color: '#666'
                }
              }
            ],
            xAxis: [
              {
                type: 'category',
                axisTick: { show: false },
                data: totalYearMonthData.dataX,
                axisLine: {
                  lineStyle: {
                    color: '#999'
                  }
                },
                axisLabel: {
                  color: '#666'
                }
              }
            ],
            series: [
              {
                name: '订单数',
                type: 'bar',
                data: totalYearMonthData.dataY,
                itemStyle: {
                  color: new echarts.graphic.LinearGradient(
                      0, 0, 0, 1,
                      [
                          {offset: 0, color: '#798BFF'},
                          {offset: 1, color: '#67F6FF'}
                      ]
                  )
              },
              }
            ],
            dataZoom : [
              {
                  show: true,
                  start: 0,
                  end: 100,
                  height:10,
                  bottom: 4
              },
              {
                  type: 'inside',
                  start: 94,
                  end: 100
              },
              {
                  show: true,
                  yAxisIndex: 0,
                  filterMode: 'empty',
                  width: 10,
                  height: '80%',
                  top: 40,
                  showDataShadow: false,
                  right: 8
              }
          ]};
          totalYearMonthChart.setOption(option);
          totalYearMonthChart.on('click',function(params) {
            var tmp = params.name.replace('月','');
            if(curMonth != tmp){
              curMonth = tmp;
              wx.showLoading({
                title: '查询中...',
              });
              requestNum = 2;
              totalThis.clickShowChildType();
              totalThis.clickForMonthOrderList();
            }
           
          });
          return totalYearMonthChart;
        }
      }
    },
    monthOrdersListBar: {
      onInit: function(canvas, width, height, dpr){
        if(totalMonthOrdersChart){

        } else if(canvas){
          chart = echarts.init(canvas, null, {
            width: width,
            height: height,
            devicePixelRatio: dpr // new
          });
          totalMonthOrdersChart = chart;
          canvas.setChart(totalMonthOrdersChart);
        }
         
        if(totalMonthOrdersChart && orderListInfo){
          let series = [],_stack,legend=[];
          for(var i in stackArr){
              if(i == '订单数量') {
                _stack = '';
              } else {
                _stack = 'complete';
              }
            series.push(
            {
                name: i,
                type: 'bar',
                emphasis: {
                    focus: 'series'
                },
                stack: _stack,
                data: stackArr[i]
            });
          }
         
            for(var index = 0;index < series.length; index++) {
                legend.push(series[index].name);
            }
            var _title = curMonth + '月订单详情';
            var option = {
                color: ['#E68853','#F5D77B','#5ECFFF'],
                title: {
                    text: _title,
                    left: 0,
                    top:0,
                    textStyle: {
                        fontSize:'14',
                        fontWeight: 600
                  }
                },
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        type: 'shadow',
                        label: {
                            show: true
                        }
                    }
                },
                legend: {
                    top: 24,
                    right:'0',
                    data: legend
                },
                calculable: true,
                grid: {
                    top: 60,
                    bottom: 24,
                    left: '0%',
                    right: 20,
                    containLabel: true
                },
                xAxis: [
                    {
                        // name:'入库成品数区间段',
                        type: 'category',
                        data: orderListInfo.dataX,
                        
                        axisTick: {
                            show: false
                        },
                        axisLine: {
                            show: false
                        }
                    }
                ],
                yAxis: [
                    {
                        type: 'value',
                        name: ''
                    }
                ],
                dataZoom: [
                    {
                        show: true,
                        start: 0,
                        end: 50,
                        height:10,
                        bottom: 0
                    },
                    {
                        type: 'inside',
                        start: 94,
                        end: 100
                    },
                    {
                        show: true,
                        yAxisIndex: 0,
                        filterMode: 'empty',
                        width: 10,
                        height: '80%',
                        showDataShadow: false,
                        right: 8
                    }
                ],
            series: series,
            };
          totalMonthOrdersChart.setOption(option);
          curOrderName = orderListInfo.dataX[0];
          totalMonthOrdersChart.on('click',function(params) {
            if(curOrderName != params.name){
              curOrderName = params.name;
              totalThis.clickForOrderInfo();
            }
          });

          totalThis.clickForOrderInfo();
          return totalMonthOrdersChart;
        }
      }
    },
    monthOrderInfoPie: {
      onInit: function(canvas, width, height, dpr){
        if(totalOrderInfoChart){}
        else if(canvas){
          chart = echarts.init(canvas, null, {
            width: width,
            height: height,
            devicePixelRatio: dpr // new
          });
          totalOrderInfoChart = chart;
          canvas.setChart(totalOrderInfoChart);
        }
       
        if(totalOrderInfoChart && orderInfoData){
          var _title = curOrderName + '订单进度';
          var option = {
            color: ['#3A80AB','#7C8BF7','#3A80AB','#89D08E','#79BAF4','#F3CA47','#E29635','#D5722B'],
            // tooltip: {
            //   trigger: 'item'
            // },
                  legend: {
                      top: '56%',
                      left: 'center'
                  },
                  title:{
                    text: _title,
                    top: 0,
                    left: 'center',
                    textStyle: {
                        fontSize:'14',
                        fontWeight: 600
                   }
                },
                series: [
                  {
                    name:_title,
                    type: 'pie',
                    radius: ['70%','100%'],
                    top: 30,
                    bottom:'50%',
                    left:'0',
                    right:'0',
                    avoidLabelOverlap: false,
                    data: orderInfoData,
                    label: {
                      show: false,
                      position: 'center'
                    },
                    emphasis: {
                        label: {
                            show: true,
                            fontSize: '14',
                            fontWeight: 'bold',
                            formatter: '{b}\n\n{c}:({d}%)'
                        }
                    },
                    labelLine: {
                        show: false
                      
                    },
                    itemStyle: {
                        borderRadius: 10,
                        borderColor: '#fff',
                        borderWidth: 2
                    }
                  
                  }
                ]
          };     
          totalOrderInfoChart.setOption(option);

          totalOrderInfoChart.hideLoading();
          return totalOrderInfoChart;
        }
     
        // getOrderInfoFun();
      }
    },
    num:0,
    showScrollTop:false,
    showCurView: true
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function () {
    wx.showLoading({
      title: '加载中...',
    });
    bodyWidth = wx.getSystemInfoSync().windowWidth;
    totalThis = this;
    let xyznzzwechatEffective = session.get("xyznzzwechatEffective");
    xyznzzwechatEffective = xyznzzwechatEffective ? xyznzzwechatEffective:0;
    // 判断当前时间，登录时效超过7天，清空缓存数据
    if(xyznzzwechatEffective <= new Date().getTime()) {
      session.allClear();
    }
    wechatUserInfo = session.get('xyznzzwechatUserInfo');
    if(wechatUserInfo && wechatUserInfo instanceof Object){
      this.setData({showDashboardBox: true});
    } else {
      this.setData({showDashboardBox: false});

      wx.redirectTo({
        url: '../syslogin/syslogin',
     })
      
    }
    this.getYearOrderFun(function(){
      totalThis.data.yearTotalPie.onInit();
    },this);
    getYearMonthOrdersFun(function(){
      totalThis.data.yearEachMonthBar.onInit();
    });
    if(bodyWidth < 390) {
      this.scrollTop();
    } else {
      this.setData({
        showCurView: false
      });
    }
    this.autoUpdate()
  },
  // 年份更换
  yearsChange: function(e){
    this.setData({
      valueYears: e.detail
    });
  },
  // 查询年度信息
  getYearInfoFun: function(){
    if(this.data.valueYears != valueYears) {
      wx.showLoading({
        title: '查询中...',
      });
      requestNum = 2;
      curMonth = '';
      curOrderName = '';
      totalMonthOrdersChart=null;
      totalOrderInfoChart=null;
      valueYears = this.data.valueYears;
      this.setData({showChildBox: false});
      // this.getYearOrderFun(function(){
      //   totalThis.data.yearTotalPie.onInit();
      // },this);
      // getYearMonthOrdersFun(function(){
      //   totalThis.data.yearTotalPie.onInit();
      //   totalThis.data.yearEachMonthBar.onInit();
      // });
      this.onLoad();
    }
  },
  // 获取年度订单
  getYearOrderFun: function(callback,that){
    wx.request({
      url: config.service.host + config.service.TestGetOrderNumberAndDeliveryNumberAndCompleteNumber,
      data: {
        year: valueYears
      },
      method: 'GET',
      header: {
        'Content-Type': 'application/json' // 默认值
        // 'Authorization': 'Bearer ' + session.get('accessToken')
      },
      success: function (res) {
        if (res.data.success) {
          var result =res.data.result;
          if(result && result instanceof Object) {
            var dataArr =[];
            dataArr.length = 3;
            var curTotalNumObj= {};
            for(var index = 0;index < result.dataX.length; index++){
              var tmpX = result.dataX[index],
                  tmpY = result.dataY[index];
                  var tmpObj = {
                    name: tmpX,
                    value: tmpY
                  };
                  if(tmpX == '订单数量'){
                    dataArr[0]=tmpObj;
                  } else if(tmpX == '完成数量'){
                    dataArr[2]=tmpObj;
                  } else {
                    dataArr[1]=tmpObj;
                  }
                curTotalNumObj[tmpX] = tmpY;
            }
           
            curTotalNumObj= curTotalNumObj;
            that.setData({
              curTotalNumObj:curTotalNumObj
            });
            totalYearChartData = dataArr;
            if(callback){
              callback();
            }
          }
         
        } else if(res.statusCode == '401'){
          wx.showToast({
            title: '登录失效，请重新登录',
            icon: 'none',
            duration: 2000,
            mask: true,
            success: function () {
              session.allClear();
              setTimeout(function(){
                wx.reLaunch({
                  url: 'pages/syslogin/syslogin'
                })
              },2000);
             
            }
          });
        }
      },
      complete:function(c){
        requestNum--;
        if(requestNum <= 0 && wechatUserInfo) {
          wx.hideLoading();
        }
      }
    })
  },
  // 点击显示、隐藏二级图表
  clickShowChildType:function(){
    this.setData({showChildBox: true});
  },
  // 点击获取某个月份的订单列表
  clickForMonthOrderList:function(){
    getMonthOrdersFun(function(){
      totalThis.data.monthOrdersListBar.onInit();
    });
  },
  // 点击获取某个订单进度
  clickForOrderInfo:function(){
    getOrderInfoFun(function(){
      totalThis.data.monthOrderInfoPie.onInit();
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },
   // 滚动
  scrollTop: function(){
    var that = this;
    function goLeft() {
        if (that.data.num == -360) {
          that.setData({
            num: 0
          });  
        }
        that.setData({
          num:  that.data.num -= 1
        }); 
    }
    //设置滚动速度
    setInterval(goLeft, 30);
  },
  // 关闭
  closeDianFun:function(){
    this.setData({
      showScrollTop: false
    })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // 获取场景值，判断是否显示加入到 “我的小程序”
    let xyznzzIsNotFirst = session.get("xyznzzIsNotFirst");
    if(!xyznzzIsNotFirst) {
      this.setData({
        showScrollTop: true
      });
      session.set("xyznzzIsNotFirst", true);
    }
    //添加选中效果
    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
      //自定义组件的getTabBar 方法，可获取当前页面下的自定义 tabBar 组件实例。
      this.getTabBar().setData({
        selected: 0 //这个是tabBar中当前页对应的下标
      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  onLaunch: function() {
    this.autoUpdate()
  },
  autoUpdate: function() {
    var self = this
    // 获取小程序更新机制兼容
    if (wx.canIUse('getUpdateManager')) {
      const updateManager = wx.getUpdateManager()
      //1. 检查小程序是否有新版本发布
      updateManager.onCheckForUpdate(function(res) {
        // 请求完新版本信息的回调
        if (res.hasUpdate) {
          //检测到新版本，需要更新，给出提示
          wx.showModal({
            title: '更新提示',
            content: '检测到新版本，是否下载新版本并重启小程序？',
            success: function(res) {
              if (res.confirm) {
                //2. 用户确定下载更新小程序，小程序下载及更新静默进行
                self.downLoadAndUpdate(updateManager)
              } else if (res.cancel) {
                //用户点击取消按钮的处理，如果需要强制更新，则给出二次弹窗，如果不需要，则这里的代码都可以删掉了
                wx.showModal({
                  title: '温馨提示~',
                  content: '本次版本更新涉及到新的功能添加，旧版本无法正常访问的哦~',
                  showCancel:false,//隐藏取消按钮
                  confirmText:"确定更新",//只保留确定更新按钮
                  success: function(res) {
                    if (res.confirm) {
                      //下载新版本，并重新应用
                      self.downLoadAndUpdate(updateManager)
                    }
                  }
                })
              }
            }
          })
        }
      })
    } else {
      // 如果希望用户在最新版本的客户端上体验您的小程序，可以这样子提示
      wx.showModal({
        title: '提示',
        content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
      })
    }
  },
  /**
   * 下载小程序新版本并重启应用
   */
  downLoadAndUpdate: function (updateManager){
    var self=this
    wx.showLoading();
    //静默下载更新小程序新版本
    updateManager.onUpdateReady(function () {
      wx.hideLoading()
      //新的版本已经下载好，调用 applyUpdate 应用新版本并重启
      updateManager.applyUpdate()
    })
    updateManager.onUpdateFailed(function () {
      // 新的版本下载失败
      wx.showModal({
        title: '已经有新版本了哟~',
        content: '新版本已经上线啦~，请您删除当前小程序，重新搜索打开哟~',
      })
    })
  }
})
  // 获取当年 每月订单
 function getYearMonthOrdersFun(callback){
    wx.request({
      url: config.service.host + config.service.TestGetOrderNumberYeearMonth,
      data: {
        year: valueYears
      },
      method: 'GET',
      header: {
        "Content-Type": "application/json", 
        "Accept": "application/json"
      },
      success: function (res) {
        if (res.data.success) {
          var result = res.data.result;
          if(result && result instanceof Object){
            totalYearMonthData = result;
            if(callback && callback instanceof Function) {
              callback();
            }
          }
        } else if(res.statusCode == '401'){
          wx.showToast({
            title: '登录失效，请重新登录',
            icon: 'none',
            duration: 2000,
            mask: true,
            success: function () {
              session.allClear();
              setTimeout(function(){
                wx.reLaunch({
                  url: 'pages/syslogin/syslogin'
                })
              },2000);
             
            }
          });
        }
      },
      fail:function(res){
      },
      complete:function(c){
        requestNum--;
        if(requestNum <= 0 && wechatUserInfo) {
          wx.hideLoading();
        }
      }
    })
  }
  // 获取当月 订单列表
 function getMonthOrdersFun(callback){
    wx.request({
      url: config.service.host + config.service.TestGetOrderNumberMonth,
      data: {
        year: valueYears,
        month: curMonth
      },
      method: 'GET',
      header: {
        'Content-Type': 'application/json' // 默认值
      },
      success: function (res) {
        if (res.data.success) {
          var result = res.data.result;
          if(result && result instanceof Object){
           
              stackArr = [];
              for(var key in result.dataYs){
                  let tmpObj = result.dataYs[key];
                  if(key == '订单数量') {
                      stackArr.push( 
                              {
                                  name: key,
                                  type: 'bar',
                                  emphasis: {
                                      focus: 'series'
                                  },
                                  data: tmpObj
                              });
                  } else {
                      stackArr.push( 
                          {
                              name: key,
                              type: 'bar',
                              stack: '完成',
                              emphasis: {
                                  focus: 'series'
                              },
                              data: tmpObj
                          });
                  }
              }
              stackArr = result.dataYs;
              orderListInfo = result;
              if(callback && callback instanceof Function){
                callback();
              }
          
          }
        } else if(res.statusCode == '401'){
          wx.showToast({
            title: '登录失效，请重新登录',
            icon: 'none',
            duration: 2000,
            mask: true,
            success: function () {
              session.allClear();
              setTimeout(function(){
                wx.reLaunch({
                  url: 'pages/syslogin/syslogin'
                })
              },2000);
             
            }
          });
        }
      },
      complete:function(c){
        requestNum--;
        if(requestNum <= 0) {
          wx.hideLoading();
        }
      }
    })
  }
  // 获取当前订单进度
function getOrderInfoFun(callback){
  wx.showLoading({
    title: '查询中...',
  });
  requestNum = 1;
    wx.request({
      url: config.service.host + config.service.TestGetOrderProductionProgress,
      data: {
        year: valueYears,
        month: curMonth,
        orderName: curOrderName
      },
      method: 'GET',
      header: {
        'Content-Type': 'application/json' // 默认值
        // 'Authorization': 'Bearer ' + session.get('accessToken')
      },
      success: function (res) {
        if (res.data.success) {
          var result = res.data.result;
          if(result && result instanceof Object){
            var dataArr = [];
            if(result && result.dataX instanceof Array) {
              for(var index = 0; index < result.dataX.length; index++) {
                  dataArr.push({value: result.dataY[index], name: result.dataX[index]});
              }
            }
         
            orderInfoData = dataArr;
            if(callback && callback instanceof Function){
              callback();
            }
          }
         
        } else if(res.statusCode == '401'){
          wx.showToast({
            title: '登录失效，请重新登录',
            icon: 'none',
            duration: 2000,
            mask: true,
            success: function () {
              session.allClear();
              setTimeout(function(){
                wx.reLaunch({
                  url: 'pages/syslogin/syslogin'
                })
              },2000);
             
            }
          });
        }
      },
      complete:function(c){
        requestNum--;
        if(requestNum <= 0) {
          wx.hideLoading();
        }
      }
    })
  }


